package cn.pugle.quartz;

import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

import static org.quartz.DateBuilder.IntervalUnit.SECOND;
import static org.quartz.DateBuilder.futureDate;
import static org.quartz.TriggerKey.triggerKey;

/**
 * todo 测试quartz的用法和内部实现原理
 * Created by tzp on 7/21/16.<br>
 */
public class QuartzTest {
    public static void main(String[] args) throws SchedulerException {
        JobDetail jobDetail = JobBuilder.newJob(MyJob.class)
                .withIdentity("myJob")
                .usingJobData("a", 1)
                .usingJobData("b", 2)
//                .storeDurably(true)
                .build();

        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(triggerKey("myTrigger", "myTriggerGroup"))
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInSeconds(5)
                        .repeatForever())
                .usingJobData("c", 3)
                .startAt(futureDate(10, SECOND))
//                .forJob("myJob")
                .build();
        //trigger和detail的关系
        //1. trigger里没设定detail。 schedule时指定了。(本类)
        //2. CronTriggerFactoryBean里的写法。(SpringQuartzTest)
        //      cti.setJobKey(this.jobDetail.getKey());
        //      cti.setJobDataMap(this.jobDataMap);this.jobDataMap.put("jobDetail", this.jobDetail);
        //      否则 Invocation of init method failed; nested exception is org.quartz.SchedulerException:
        //      Trigger's related Job's name cannot be null at org.quartz.impl.triggers.AbstractTrigger.validate(AbstractTrigger.java:763)
        //3. builder时带着jobName等jobKey，就去schedule查找。(本类注释掉的)
        //      The job (DEFAULT.myjob) referenced by the trigger does not exist.
        //      Trigger's related Job's name cannot be null
        //


        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
        scheduler.start();
        scheduler.scheduleJob(jobDetail, trigger);
//        scheduler.addJob(jobDetail, false);
//        scheduler.scheduleJob(trigger);
    }


}
